package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;

@RestController
@Slf4j
public class FileController {
    @GetMapping("/go-upload")
    public ModelAndView goUpload(){
        return new ModelAndView("upload");
    }

    @PostMapping("/upload")
    public ModelAndView getFile(@RequestParam("file")MultipartFile file){
        log.error("............");
        //图片校验（图片是否为空,图片大小，上传的是不是图片、图片类型（例如只能上传png）等等）
        if (file.isEmpty()) {
            throw new RuntimeException("图片上传失败");
        }
        String originalFilename = file.getOriginalFilename();
        //拼接图片上传的路径 url+图片名
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\images\\";
        String path = pre + originalFilename;
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ModelAndView index = new ModelAndView();
        index.setViewName("showImg");
        index.addObject("img","images/"+originalFilename);
        return index;
    }
}
